﻿
using AutoMail.Tools;

namespace AutoMail.Log
{
    public class MyLogger : ILogger
    {
        private readonly string _name;
        private readonly IConfiguration _config;
        private LogLevel _logLevel;

        public MyLogger(string name, IConfiguration config)
        {
            _name = name;
            _config = config;
        }

        public IDisposable BeginScope<TState>(TState state)
        {
            return null;
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            string? logLevelName = _config["Logging:LogLevel:Default"];
            LogLevel curLogLevel = LogLevel.Information;
            if (!string.IsNullOrEmpty(logLevelName))
            {
                curLogLevel = Utils.GetEnumValueByName<LogLevel>(logLevelName);
            }

            return curLogLevel <= logLevel;
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }
            _logLevel = logLevel;
            FileLog($"{DateTime.Now.ToString("yyyy-MM-dd hh:mm:fff")} - {logLevel.ToString()} - {_name} - {formatter(state, exception)}");
        }

        private async void FileLog(string strLog)
        {
            string fileName = DateTime.Now.ToString("yyyy-MM-dd") + "_" + _logLevel.ToString();
            string logFileExtention = ".txt";

            try
            {
                // Trying log txt
                string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName, logFileExtention);
                await File.AppendAllTextAsync(filePath, strLog);
            }
            catch (Exception)
            {
                // Trying log to a new file
                string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName + Guid.NewGuid().ToString() + logFileExtention);
                await File.AppendAllTextAsync(filePath, strLog);
            }
        }
    }
}
